'''
Created on Apr 29, 2010

@author: Juan
'''

import sys
import os
import logging
import logging.handlers
import config_read

def main():
    '''
    The main execution point for the server
    '''
    process_config(get_config())
    init_logger()

def get_config():
    ## Loads the configuration file into memory
    cl = config_read.ConfigLoader()
    try:
        config = cl.load(str(sys.argv[1])) # If an argument is specified, it uses that path
    except:
        print "No configuration file specified, trying to load default config"
        config = cl.load('conf/server.cfg') # If no argument, the default is used
    
    return config
    
def process_config(options):
    ALLOWED_OPTIONS = ('reload_config', 'foo')
#   ALLOWED_SECTIONS = ('Section1', 'Section2', 'Section3')
    
    for o in ALLOWED_OPTIONS:
        if(o in options):
            func_call = str(o) + "(" + str(options[o]) + ")"
            print func_call
            eval(func_call)

def init_logger(logLevel="debug", logFile="log/agent.log", loggerName="agent"):
        LEVELS = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
              'critical': logging.CRITICAL}
        
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        
        # Sanitize the logLevel
        logLevel = logLevel.lower()
        
        # Set up the logger object with the base name of 'agent' and a default
        #    logLevel of logging.INFO if no logLevel is specified
        log = logging.getLogger(loggerName) # The logger name should be based on the config file
        log.setLevel(LEVELS[logLevel])
        
        fh = logging.FileHandler(logFile)
        
        if (logLevel == 'debug'):
            ch = logging.StreamHandler()
            ch.setLevel(LEVELS[logLevel])
            ch.setFormatter(formatter)
            log.addHandler(ch)
        
        
        fh.setFormatter(formatter)
        log.addHandler(fh)
        
        log.info("initializing logger")

if __name__ == '__main__':
    main()